import { APPROVAL_VULNERABILITY_STATES, NEWLY_DETECTED } from '../scan_filters/constants';

// Value `newly_detected` was expanded and maps to both `new_needs_triage` and `new_dismissed`.
// In order to avoid breaking changes, it is transformed to the new statuses to be able
// to read policies containing `newly_detected` status.
// https://gitlab.com/groups/gitlab-org/-/epics/6826#note_1341377224
const transformNewlyDetectedState = (states) => {
  if (states.includes(NEWLY_DETECTED)) {
    return Array.from(
      new Set([...states, ...Object.keys(APPROVAL_VULNERABILITY_STATES[NEWLY_DETECTED])]),
    );
  }
  return states;
};

/**
 * This function groups vulnerability states into their corresponding groups.
 * `newly_detected` state is transformed into `new_needs_triage` + `new_dismissed`.
 * @param {Array} states - List of vulnerability_states for a rule
 * @returns {Object} - Grouped states by state groups. Empty groups are omitted.
 */
export const groupSelectedVulnerabilityStates = (states) => {
  const transformedStates = transformNewlyDetectedState(states);

  return Object.entries(APPROVAL_VULNERABILITY_STATES).reduce(
    (selected, [vulnerabilityStatusGroup, vulnerabilityState]) => {
      const statesForGroup = transformedStates.filter((state) =>
        Object.keys(vulnerabilityState).includes(state),
      );
      if (statesForGroup.length) {
        return { ...selected, [vulnerabilityStatusGroup]: statesForGroup };
      }
      return selected;
    },
    {},
  );
};
